/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */

package io.iec.edp.caf.tenancy.core;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 内存缓存，临时解决DbConnectionId重复问题，待su可以配置之后，生成随机id,再切回分布式缓存
 * @author wangyandong
 */
public class MemoryCache {
    private final HashMap<String, Object> map = new HashMap<>();

    /**
     * 获取缓存
     * @param key 键
     * @param clazz 自定义对象的class对象
     * @return 缓存值
     */
    public <T> T get( String key, Class<T> clazz){
        Object data = this.map.get(key);
        return (T)data;
    }

    /**
     * 增加缓存
     * @param key 键
     * @param value 类值
     */
    public void set(String key, Object value){
        this.map.put(key,value);
    }

    /**
     * 增加缓存
     * @param hashKey hash键
     * @param key 键
     * @param value  值
     */
    public void hashSet(String hashKey, String key, Object value){
        HashMap<String,Object> hashMap = (HashMap<String, Object>) this.map.get(hashKey);
        if(hashMap==null){
            hashMap = new HashMap<>();
            this.map.put(hashKey,hashMap);
        }
        hashMap.put(key,value);
    }

    /**
     * 获取缓存
     * @param hashKey hash键
     * @param members 字段列表
     * @param clazz 自定义对象的class对象
     * @return 缓存值
     */
    public <T> T[] hashMemberGet(String hashKey, String[] members,Class<T>clazz){
        HashMap<String,Object> hashMap = (HashMap<String, Object>) this.map.get(hashKey);
        if(hashMap!=null){
            List<T> list = new ArrayList<T>();
            for(String item : members){
                if(hashMap.containsKey(item))
                    list.add((T)hashMap.get(item));
            }
            if(list.size()>0){
                T[] result = (T[]) Array.newInstance(clazz, list.size());
                return list.toArray(result);
            }
        }
        return null;
    }

    /**
     * 删除缓存
     * @param key 键
     */
    public void remove(String key){
        this.map.remove(key);
    }

    /**
     * 删除缓存
     * @param hashKey hash键
     * @param key  键
     */
    public void hashRemove(String hashKey,String key){
        HashMap<String,Object> hashMap = (HashMap<String,Object>)this.map.get(hashKey);
        if(hashMap!=null){
            hashMap.remove(key);
        }
    }
}
